<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Order;

use Kcdns\Service\File\Model;
use Think\Log;

class Order extends \Service\Common\BaseModel
{
    protected $name = 'order';

    const ORDER_STATUS_SUBMIT = 0;//已下单
    const ORDER_STATUS_PAID = 1;//已支付
    const ORDER_STATUS_DELIVERED = 2;//已发货
    const ORDER_STATUS_RECEIVED = 3;//已收货
    const ORDER_STATUS_CANCEL = 4;//已取消

    const ORDER_STATUS_LABEL = [
        self::ORDER_STATUS_SUBMIT => '已下单',
        self::ORDER_STATUS_PAID => '已支付',
        self::ORDER_STATUS_DELIVERED => '已发货',
        self::ORDER_STATUS_RECEIVED => '已收货',
    ];

    const PAY_TYPE_BALANCE = 1;//余额支付
    const PAY_TYPE_FRIEND = 2;//代付
    const PAY_TYPE_WXH5 = 3;//微信h5支付
    const PAY_TYPE_WXJS = 4;//微信公众号支付

    const PAY_TYPE_LABEL = [
        self::PAY_TYPE_BALANCE => '余额支付',
        self::PAY_TYPE_FRIEND => '代付',
    ];

    const FRIEND_STATUS_SUBMIT = 0;//已提交
    const FRIEND_STATUS_PAID = 1;//已支付
    const FRIEND_STATUS_REJECT = 2;//已拒绝

    //收货
    public function received($order_no, $uid)
    {
        $order = $this->where([
            'uid' => $uid,
            'order_no' => $order_no,
        ])->find();
        if (!$order) {
            throw new \Exception("无效的订单");
        }

        if ($order['order_status'] != self::ORDER_STATUS_DELIVERED) {
            throw new \Exception("无效的订单状态");
        }

        $this->save([
            'id' => $order['id'],
            'order_status' => self::ORDER_STATUS_RECEIVED
        ]);
    }

    //发货
    public function express($order_id, $express_company, $express_no)
    {
        $order = $this->find($order_id);
        if (!$order) {
            throw new \Exception("无效的订单");
        }

        if ($order['order_status'] != self::ORDER_STATUS_PAID) {
            throw new \Exception("无效的订单状态");
        }

        $this->save([
            'id' => $order_id,
            'express_company' => $express_company,
            'express_no' => $express_no,
            'express_time' => date('Y-m-d H:i:s'),
            'order_status' => self::ORDER_STATUS_DELIVERED
        ]);

        //发送通知
        OE('user')->addOrderExpress($order);
    }

    //拒绝代付
    public function inviteReject($order_no, $reason, $uid)
    {
        $result = M('order_friend')->where([
            'order_no' => $order_no,
            'invite_uid' => $uid,
        ])->find();
        if (!$result) {
            throw new \Exception("无效的代付订单");
        }

        if ($result['friend_status'] != self::FRIEND_STATUS_SUBMIT) {
            throw new \Exception("无效的代付状态");
        }

        M('order_friend')->save([
            'id' => $result['id'],
            'friend_status' => self::FRIEND_STATUS_REJECT,
            'reason' => $reason,
            'update_time' => date('Y-m-d H:i:s')
        ]);

        return true;
    }

    //订单统计
    public function getStatusNum($uid)
    {
        $list = M('order')->field('count(*) total,order_status')->where(['uid' => $uid, 'is_invite' => 0])->group('order_status')->select();
        $result = [];
        $total = [];
        foreach ($list as $row) {
            $result[$row['order_status']] = $row['total'];
            $total[] = $row['total'];
        }
        $order_invite_num = M('order')->where(['invite_uid' => $uid])->count();
        return [
            'total_order' => array_sum($total),
            'order_invite_num' => $order_invite_num,
            'order_unpaid_num' => (int)$result[self::ORDER_STATUS_SUBMIT],
            'order_paid_num' => (int)$result[self::ORDER_STATUS_PAID],
            'order_send_num' => (int)$result[self::ORDER_STATUS_DELIVERED],
            'order_receive_num' => (int)$result[self::ORDER_STATUS_RECEIVED],
        ];
    }

    //普通订单
    public function submit($data, $uid)
    {
        try {
            $this->startTrans();
            //创建订单
            $order_no = $this->_submit($data, $uid, $is_invite = 0);
            $this->commit();
            return $order_no;
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //代付订单
    public function submitInvite($data, $uid, $login_info)
    {
        $user = M('user')->where([
            'mobile' => $data['mobile'],
        ])->find();
        if (!$user) {
            throw new \Exception("未找到匹配的代付用户");
        }

        if (!$user['is_leader']) {
            //throw new \Exception("该用户没有代付权限");
        }

        if ($user['uid'] == $uid) {
            throw new \Exception("不能代付自己的订单");
        }

        try {
            $this->startTrans();
            //创建订单
            $order_no = $this->_submit($data, $uid, $invite_uid = $user['uid']);
            //发送邀请
            $insert_id = M('order_friend')->add([
                'uid' => $uid,
                'invite_uid' => $user['uid'],
                'order_no' => $order_no,
                'mobile' => $data['mobile'],
                'real_name' => $user['real_name'],
                'create_time' => date('Y-m-d H:i:s')
            ]);
            if (!$insert_id) {
                throw new \Exception("发送邀请失败");
            }
            //收到代付通知
            OE('user')->receiveInvitePay([
                'uid' => $user['uid'],
                'from_name' => $login_info['real_name'],
                'order_no' => $order_no,
            ]);
            $this->commit();
            return $order_no;
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //获取订单附表
    protected function createOrderGoods($goods_arr, $uid, $spec_arr)
    {
        $has_get_point = false;//是否获取过用户可用积分
        $total_point = 0;
        $list = [];
        foreach ($goods_arr as $goods_id => $buy_num) {
            $goods = OE('goods')->getDetail($goods_id, $uid);
            if ($goods['max_buy'] && (M('order_goods')->where(['uid' => $uid, 'order_id' => $goods_id])->sum('buy_num') + $buy_num) > $goods['max_buy']) {
                throw new \Exception(str_replace('[MAX_BUY]', $goods['max_buy'], C('max_buy_tip', null, '该商品最多共限购[MAX_BUY]个')));
            }

            if ($buy_num > $goods['stock']) {
                throw new \Exception("库存不足");
            }

            $user_data = M('user')->where(['uid' => $uid])->find();
            $goods_deviation_point = 0;
            if ($goods['deviation_point']) {
                if (!$has_get_point) {
                    $total_point = M('user')->where(['uid' => $uid])->getField('total_point');//用户积分
                    $has_get_point = true;
                }

                if ($total_point > 0) {
                    $max_deviation_point = $goods['deviation_point'] * $buy_num;
                    $goods_deviation_point = $total_point >= $max_deviation_point ? $max_deviation_point : $total_point;//商品抵扣积分
                    $total_point -= $goods_deviation_point;
                }
            }

            $contribution = $goods['is_rebuy'] ? $goods['rebuy_contribution'] : $goods['contribution'];
            $contribution = $contribution > 0 ? $contribution : 0;
            $goods_contribution = $contribution * $buy_num;//商品贡献
            $goods_give_point = $goods['give_point'] * $buy_num;//商品可获积分
            $goods_total_money = $buy_num * ($user_data['vip_level'] ? self::getPrice($goods, $buy_num) : $goods['sell_price']);//商品应付金额
            $goods_pay_money = $goods_total_money - $goods_deviation_point;//商品实付金额

            $list[] = [
                'uid' => $uid,
                'goods_id' => $goods_id,
                'title' => $goods['title'],
                'sell_price' => $goods['is_rebuy'] ? self::getPrice($goods, $buy_num) : $goods['sell_price'],
                'goods_total_money' => $goods_total_money,
                'goods_pay_money' => $goods_pay_money,
                'goods_give_point' => $goods_give_point,
                'goods_contribution' => $goods_contribution,
                'buy_num' => $buy_num,
                'goods_deviation_point' => $goods_deviation_point,
                'postage' => $goods['postage'],
                'goods_json' => json_encode($goods, JSON_UNESCAPED_UNICODE),
                'create_time' => date('Y-m-d H:i:s'),
                'spec_list' => $spec_arr[$goods_id]?$spec_arr[$goods_id]:''
            ];
        }
        return $list;
    }

    public function getPrice($goods, $buy_count){
        if($buy_count<$goods['sum_1']){
            $price = $goods['price_1'];
        }elseif($buy_count>=$goods['sum_1'] && $buy_count<$goods['sum_2']){
            $price = $goods['price_2'];
        }elseif($buy_count>=$goods['sum_2'] && $buy_count<$goods['sum_3']){
            $price = $goods['price_3'];
        }else{
            $price = $goods['price_3'];
        }
        return $price;
    }

    //订单提交
    protected function _submit($data, $uid, $invite_uid = 0)
    {
        $goods_arr = $data['goods'];
        $spec_arr = $data['spec'];
        $address_id = $data['address_id'];
        $red_packets = $data['red_packets'];
        $remark = $data['remark'];

        $order_no = $this->genOrderNo();

        $is_invite = $invite_uid ? 1 : 0;
        $address = OE('address')->getDetail($address_id, $uid);

        $order_contribution = 0;//订单贡献
        $deviation_point = 0;//订单积分抵扣
        $total_money = 0;//订单应付金额
        $pay_money = 0;//订单实付金额
        $give_point = 0;//订单可获积分
        $total_postage = 0;//订单邮费

        $order_goods = $this->createOrderGoods($goods_arr, $uid, $spec_arr);
        foreach ($order_goods as $row) {
            //订单累计
            $give_point += $row['goods_give_point'];
            $order_contribution += $row['goods_contribution'];
            $deviation_point += $row['goods_deviation_point'];
            $total_money += $row['goods_total_money'];
            $pay_money += $row['goods_pay_money'];

            $total_postage += $row['postage'];
        }
        if(count($goods_arr) > 1){
	         if ($pay_money < 100) {
	         	$total_postage = 20;
	         }else{
	         	$total_postage = 10;
	         }
        }
        //订单服务费抵扣
        $friend_fee_percent = 0;
        $friend_fee_money = 0;
        if ($is_invite) {
            $leader_level = M('user')->where(['uid' => $invite_uid])->getField('leader_level');
            $level_list = get_list_config('LEADER_LEVEL', $all = true);
            $friend_fee_percent = $level_list[$leader_level]['percent'] ?: 0;
            $friend_fee_money = get_decimal($order_contribution * $friend_fee_percent);

            $total_money -= $friend_fee_money;
            $pay_money -= $friend_fee_money;
        }

        //邮费
        $postage = $total_money >= C('FREE_MIN_MONEY') ? 0 : $total_postage;
        if($this->isRemoteArea($address['area'])) $postage += 10;
        $total_money += $postage;
        $pay_money += $postage;

        //红包检测
        $use_red_packets = 0;
        if ($red_packets) {
            $has_red_packets = M('user')->where(['uid' => $uid])->getField('red_packets');
            if ($has_red_packets < $red_packets || $has_red_packets == 0) {
                throw new \Exception("可用红包不足");
            }

            $use_red_packets = min($pay_money, $red_packets);
            $pay_money -= $use_red_packets;
            OE('user')->useRedInOrder($uid, $order_no, $use_red_packets);
        }

        if($pay_money<$total_money) throw new \Exception('购买下单异常');

        try {
            $this->startTrans();
            $user_detail = O('user')->getUserInfo($uid);
            if($user_detail['vip_level'] > 0){
                $order_type = 1;
            }else{
                $order_type = 0;
            }
            //下单
            $order_id = $this->add([
                'uid' => $uid,
                'invite_uid' => $invite_uid,
                'order_contribution' => $order_contribution,
                'postage' => $postage,
                'address_json' => json_encode($address),
            	'area'=>$address['area'],
            	'address'=>$address['address'],
            	'mobile'=>$address['mobile'],
            	'consignee'=>$address['name'],
                'total_money' => $total_money,
                'pay_money' => $pay_money,
                'is_invite' => $is_invite,
                'friend_fee_percent' => $friend_fee_percent,
                'friend_fee_money' => $friend_fee_money,
                'deviation_point' => $deviation_point,
                'give_point' => $give_point,
                'order_no' => $order_no,
                'order_status' => self::ORDER_STATUS_SUBMIT,
                'create_time' => date('Y-m-d H:i:s'),
                'use_red_packets' => $use_red_packets,
                'order_type' => $order_type,
                'remark' => $remark,
            ]);
            if (!$order_id) {
                throw new \Exception("下单失败");
            }

            //订单附表
            foreach ($order_goods as $row) {
                $insert_id = M('order_goods')->add(array_merge($row, ['order_id' => $order_id]));
                if (!$insert_id) {
                    throw new \Exception("插入订单附表失败");
                }
            }

            //清空购物车
            OE('order')->emptyCart($uid);

            //积分记录
            if ($deviation_point) {
                OE('user')->addDeviationPoint($uid, $order_id, "订单号{$order_no}", -$deviation_point);
            }

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }

        return $order_no;
    }

    public function isRemoteArea($area){
        $remote_area = array(5, 26, 31);
        $area_arr = explode(',', $area);
        if(in_array($area_arr[0], $remote_area)){
            return true;
        }else{
            return false;
        }
    }

    //生成订单号
    public function genOrderNo()
    {
        $str = substr(md5(microtime(true)), 8, 16);
        $letters = range('a', 'z');
        $arr = array_map(function ($char) use ($letters) {
            return is_numeric($char) ? $char : array_search($char, $letters);
        }, str_split($str));
        return join('', $arr);
    }

    //删除订单
    public function remove($order_no, $uid)
    {
        $order = $this->getDetailByOrderNO($order_no, $uid);
        if ($order['uid'] != $uid || $order['pay_status'] == 1) {
            throw new \Exception("非法操作");
        }

        try {
            $this->startTrans();
            //删除订单
            $this->delete($order['id']);
            //删除代付订单
            M('order_friend')->where(['order_no' => $order_no])->save([
                'order_status' => self::ORDER_STATUS_CANCEL
            ]);
            //积分记录
            if ($order['deviation_point']) {
                OE('user')->addCancelPoint($uid, $order['id'], "订单号{$order_no}", $order['deviation_point']);
            }

            //红包恢复
            if ($order['use_red_packets']) {
                OE('user')->backRedByCancel($uid, $order['order_no'], $order['use_red_packets']);
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    //订单支付
    public function pay($data, $uid)
    {
        //支付前订单验证
        $order = $this->checkPayOrder($data['order_no'], $uid);

        if ($order['pay_money'] == 0) {
            $this->paySuccess($order, self::PAY_TYPE_BALANCE);
            return;
        }

        //支付方式
        switch ($data['pay_type']) {
            case self::PAY_TYPE_WXJS://微信公众号支付
                return $this->wxPay($order, 'wxjs');
            case self::PAY_TYPE_WXH5://微信h5支付
                return $this->wxPay($order, 'wxh5');
            case self::PAY_TYPE_BALANCE://余额支付
                //验证支付密码
                OE('user')->checkPayPassword($uid, $data['pay_password']);
                //余额支付
                $this->balancePay($order, $uid);
                break;
            default:
                throw new \Exception("无效的支付方式");
        }
    }

    //微信支付
    protected function wxPay($order, $pay_type)
    {

        $data = [
            'orderNo' => $order['order_no'], // 订单号
            'amount' => $order['pay_money'], // 支付金额
            'payType' => $pay_type, // 支付类型 Weixin Alipay
            'orderTitle' => "订单号{$order['order_no']}", // 订单名称
        ];
        /*if($order['is_order_deal'] == 0){
            if($order['postage'] == 0){
                $pay_m = $order['pay_money']+6;
                $Model = new \Think\Model();
                $Model->table('__ORDER__')->where(array('order_no' => $order['order_no']))
                    ->save(array(
                        'pay_money' => $pay_m,
                        'is_order_deal' => 1
                    ));
                $data['amount'] += 6;
            }
        }*/




        //公众号支付获取openid
        if ($pay_type == 'wxjs') {
            $uid = $order['invite_uid'] ?: $order['uid'];
            $openid = M('oauth')->where(['type' => 'weixin', 'user_id' => $uid])->getField('openid');
            if (!$openid) {
//                redirect(I('get.jump_url','/index/oauth'));
                throw new \Exception("请重新登录");

            }
            $data['extra']['openid'] = $openid;
        }

        return OE('pay')->pay($data);
    }

    //余额支付
    public function balancePay($order, $uid)
    {

        /*if($order['is_order_deal'] == 1){
            if($order['postage'] == 0){
                $pay_m = $order['pay_money']-6;
                $Model = new \Think\Model();
                $Model->table('__ORDER__')->where(array('order_no' => $order['order_no']))
                    ->save(array(
                        'pay_money' => $pay_m,
                    ));
                if($pay_m<$order['total_money']) throw new \Exception('购买下单异常');
            }
        }*/



        try {
            $this->startTrans();

            //验证余额
            OE('user')->pay($uid, -$order['pay_money'], $order);
            //支付回调
            $this->paySuccess($order, self::PAY_TYPE_BALANCE);

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //第三方支付
    public function payCallback($payment)
    {
        try {
            $this->startTrans();

            $order = $this->getDetailByOrderNO($payment['order_no']);
            //验证金额
            if (!APP_DEBUG && $payment['amount'] != $order['pay_money']) {
                throw new \Exception("支付金额和订单实付金额不一致");
            }
            switch ($payment['pay_type']) {
                case 'wxh5':
                    $pay_type = self::PAY_TYPE_WXH5;
                    break;
                case 'wxjs':
                    $pay_type = self::PAY_TYPE_WXJS;
                    break;
            }
            $this->paySuccess($order, $pay_type);

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    //验证支付订单
    protected function checkPayOrder($order_no, $uid)
    {
        $order = $this->getDetailByOrderNO($order_no, $uid);

        if ($order['pay_status'] == 1) {
            throw new \Exception("该订单已支付");
        }

        $list = M('order_goods')->where(['order_id' => $order['id']])->select();
        foreach ($list as $row) {
            //商品发生变化验证 库存在支付时验证 免得锁库存
            $goods = OE('goods')->getDetail($row['goods_id'], $uid);
            $order_goods = json_decode($row['goods_json'], true);
            if (
                $goods['title'] != $order_goods['title'] ||
                $goods['sell_price'] != $order_goods['sell_price'] ||
                $goods['supply_price'] != $order_goods['supply_price'] ||
                $goods['postage'] != $order_goods['postage'] ||
                $goods['stock'] < $order_goods['buy_num']
            ) {
                throw new \Exception("商品信息已发生变化，请重新提交订单");
            }
        }

        if (!((!$order['invite_uid'] && $order['uid'] == $uid) || ($order['invite_uid'] && $order['invite_uid'] == $uid))) {
            throw new \Exception("不是你的订单不能支付");
        }

        return $order;
    }

    //支付成功的回调
    protected function paySuccess($order, $pay_type)
    {
        if ($order['pay_status'] == 1) {
            throw new \Exception("该订单已支付");
        }

        $uid = $order['invite_uid'] ?: $order['uid'];

        //修改订单状态
        $update = $this->save([
            'id' => $order['id'],
            'order_status' => self::ORDER_STATUS_PAID,
            'pay_status' => 1,
            'pay_type' => $pay_type,
            'pay_time' => date('Y-m-d H:i:s'),
            'pay_uid' => $uid,
        ]);
        if ($update === false) {
            throw new \Exception("商品更新失败");
        }
        //更新商品 库存 销量
        $list = M('order_goods')->where(['order_id' => $order['id']])->select();
        foreach ($list as $row) {
            $update = M('goods')->save([
                'id' => $row['goods_id'],
                'stock' => ['exp', "stock-{$row['buy_num']}"],
                'sell_num' => ['exp', "sell_num+{$row['buy_num']}"],
            ]);
            if ($update === false) {
                throw new \Exception("商品更新失败");
            }
        }
        //积分记录
        if ($order['give_point']) {
            OE('user')->addGivePoint($order['uid'], $order['id'], "订单号{$order['order_no']}", $order['give_point']);
        }
        //代付订单处理
        if ($order['is_invite']) {
            $this->payInviteCallback($order);
        }
        //获取待结算记录
//        $settle_list = OE('order')->addSettle($order);
//        foreach ($settle_list as $settle) {
//            //佣金结算
//            $this->payCommissionCallback($settle);
//        }

        //自身消费累计+升级
        OE('user')->increaseSelfBuy($order['uid'], $order['pay_money']);

        //团队业绩
        $this->team($order);

        //佣金结算
        OE('user')->payCommissionCallback($order);


    }

    //佣金结算
    public function payCommissionCallback($settle)
    {
        //用于结算佣金标识
        $settle['settle_id'] = $settle['id'];

        //销售提成
        $this->saleCommission($settle);
        //管理层提成
        $this->manageCommission($settle);
        //结算状态
        OE('order')->setSettle($settle['id']);
    }

    //代付支付处理
    protected function payInviteCallback($order)
    {
        //更新代付状态
        $update = M('order_friend')->where([
            'order_no' => $order['order_no'],
        ])->save([
            'update_time' => date('Y-m-d H:i:s'),
            'friend_status' => self::FRIEND_STATUS_PAID,
        ]);
        if ($update === false) {
            throw new \Exception("代付状态更新失败");
        }

        //佣金日志
       // OE('user')->addPayCommission($order['invite_uid'], $order['friend_fee_money'], $order['friend_fee_percent'], $order);
    }

    //获取管理级别佣金比例
    public function getManagePercent($current_level, $prev_level)
    {
        $inc_percent = 0;
        $level_list = get_list_config('MANAGE_LEVEL', $all = true);
        foreach ($level_list as $key => $value) {
            if ($key > $prev_level && $key <= $current_level) {
                $inc_percent += $value['percent'];
            }
        }
        return $inc_percent;
    }

    //管理层提成
    public function manageCommission($settle)
    {
        $find_level = (int)C('FIND_LEVEL', null, 0);
        //推荐人树
        $referer_tree = OE('user')->getRefererTree($settle['uid'], 0, $find_level);
        $prev_level = 0;
        foreach ($referer_tree as $row) {
            if (!$row['manage_level']) {
                continue;
            }

            $manage_percent = $this->getManagePercent($row['manage_level'], $prev_level);
            $prev_level = $row['manage_level'];

            //佣金记录
            $money = get_decimal($settle['order_contribution'] * $manage_percent);
            OE('user')->addManageCommission($row['uid'], $money, $manage_percent, $settle);

            //资金记录
            OE('user')->commissionManage($row['uid'], $money, $settle['id']);
        }
    }

    //销售提成
    public function saleCommission($settle)
    {
        $commission = [
            C('SALE_COMMISSION1', null, 0),
            C('SALE_COMMISSION2', null, 0)
        ];

        //推荐人树
        $referer_tree = OE('user')->getRefererTree($settle['uid'], count($commission));
        foreach ($referer_tree as $key => $row) {
            $level = $key + 1;

            //佣金记录
            $money = get_decimal($settle['order_contribution'] * $commission[$key]);
            OE('user')->addSaleCommission($row['uid'], $money, $commission[$key], $settle, $level);

            //资金记录
            OE('user')->commissionSale($row['uid'], $money, $settle['id'], $level);
        }
        return true;
    }

    //团队业绩
    public function team($order)
    {
        //推荐人树
        $referer_tree = OE('user')->getRefererTree($order['uid']);
        foreach ($referer_tree as $key => $row) {
            //团队业绩
            OE('user')->addTeamContribution($row['uid'], $order);
            //计算团队业绩时判断上代们是否达到升级标准

            OE('user')->upgradeVipLevel($row['uid']);
        }
    }

    //订单详情
    public function getDetailByOrderNO($order_no, $uid = 0)
    {
        $where = [
            'order_no' => $order_no,
        ];
        $result = $this->where($where)->find();
        if (!$result) {
            throw new \Exception("无效的订单");
        }

        if ($uid) {
            //不是自己的订单  也不是代付订单
            if (!($result['uid'] == $uid || $result['invite_uid'] == $uid)) {
                throw new \Exception("无效的订单");
            }
        }

        return $this->format($result, $uid);
    }

    //订单
    public function info($id)
    {
        $order = $this->find($id);
        if (!$order) {
            throw new \Exception("无效的订单");
        }
        return $this->format($order);
    }

    //订单列表
    public function lists($order_status, $uid, $page_num = 1, $page_size = 5)
    {
        $where = [
            'uid' => $uid,
            'order_status' => $order_status,
            'is_invite' => 0,
        ];
        $list = (array)$this->where($where)->order('id desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        return [
            $this->format($list, $uid),
            $page_count = $count,
            $page_total = ceil($count / $page_size)
        ];
    }

    //邀请代付
    protected function _inviteList($uid, $friend_status, $page_num = 1, $page_size = 5, $field)
    {
        $where = [
            "a.$field" => $uid,
            'a.friend_status' => $friend_status,
        ];

        $list = (array)$this
            ->field('a.invite_uid,a.friend_status,a.reason,b.*')
            ->table('__ORDER_FRIEND__ a')
            ->join('__ORDER__ b on b.order_no=a.order_no')
            ->where($where)
            ->order('a.id desc')
            ->page($page_num, $page_size)
            ->select();

        $count = $this
            ->table('__ORDER_FRIEND__ a')
            ->join('__ORDER__ b on b.order_no=a.order_no')
            ->where($where)
            ->count();

        return [
            $this->format($list, $uid),
            $page_count = $count,
            $page_total = ceil($count / $page_size)
        ];
    }

    //我邀请别人代付
    public function meInviteList($uid, $friend_status, $page_num = 1, $page_size = 5)
    {
        return $this->_inviteList($uid, $friend_status, $page_num, $page_size, $field = 'uid');
    }

    //别人邀请我代付
    public function inviteMeList($uid, $friend_status, $page_num = 1, $page_size = 5)
    {
        return $this->_inviteList($uid, $friend_status, $page_num, $page_size, $field = 'invite_uid');
    }

    //格式化
    public function format($list, $uid = 0)
    {
        if (!$list) {
            return $list;
        }

        $is_one = count($list) == count($list, 1);
        $list = $is_one ? [$list] : $list;

        foreach ($list as &$row) {
            $goods_list = [];
            $goods_arr = M('order_goods')->where(['order_id' => $row['id']])->select();
            foreach ($goods_arr as $key => $item) {
                //商品贡献
                $json = json_decode($item['goods_json'], true);
                $goods = array_merge($item, $json);
                $goods_list[] = $goods;
            }

            $row['goods'] = $goods_list;
            $row['pay_type_label'] = self::PAY_TYPE_LABEL[$row['pay_type']];
            $row['order_status_label'] = self::ORDER_STATUS_LABEL[$row['order_status']];

            $address = json_decode($row['address_json'], true);
            $row['address'] = $address;

            //订单归属人
            $user = M('user')->where(['uid' => $row['uid']])->find();
            $row['order_owner'] = $user['real_name'];
            $row['order_owner_mobile'] = $user['mobile'];

            //代付订单
            if ($row['is_invite']) {
                //是否是我邀请的代付
                $row['is_my_invite'] = $row['uid'] == $uid ? 1 : 0;

                //代付人姓名
                $friend = M('order_friend')->where(['order_no' => $row['order_no']])->find();
                $row['friend_mobile'] = $friend['mobile'];
                $row['friend_name'] = $friend['real_name'];
            }
        }
        return $is_one ? $list[0] : $list;
    }
}